package test

import (
	"github.com/redis/go-redis/v9"
	"gorm.io/gen"
	"gorm.io/gen/field"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"utilx/dbx"
)

func GetMysql(nu int) *gorm.DB {
	switch nu {
	case 0:
		postgres, err := dbx.InitPostgres(dbx.DataBase{
			Username: "postgres",
			Password: "af12g3k4SHF",
			Host:     "[2001:41d0:a:2a7a:8888:8888:016a:a68c]:5432",
			DataBase: "nail",
		})
		if err != nil {
			panic(err)
		}
		return postgres
	case 1:
		postgres, err := dbx.InitPostgres(dbx.DataBase{
			Username: "postgres",
			Password: "af12g3k4SHF",
			Host:     "192.168.8.20:5432",
			DataBase: "nail",
		})
		if err != nil {
			panic(err)
		}
		return postgres
	default:
		panic("ss")
	}

	return nil
}
func GetRedis(nu int) *redis.Client {
	switch nu {
	case 1:
		initRedis, err := dbx.InitRedis(dbx.DataBase{
			Username: "",
			Password: "bbyWL0iXGDqGgjXuN0Ms",
			Host:     "67.21.86.154:6379",
			DataBase: "1",
		})
		if err != nil {
			return nil
		}
		return initRedis
	}
	return nil
}
func Gen(mysql *gorm.DB, models map[string]schema.Tabler,
	dataMap map[string]func(gorm.ColumnType) (dataType string),
	modelPath, outPath string, opts ...gen.ModelOpt) {
	generator := gen.NewGenerator(gen.Config{
		ModelPkgPath:     modelPath,
		OutPath:          outPath,
		FieldWithTypeTag: true, // generate with gorm column type tag
		Mode:             gen.WithDefaultQuery,
		//Mode:             gen.WithDefaultQuery | gen.WithQueryInterface,
	})
	generator.UseDB(mysql)
	//var dataMap = map[string]func(gorm.ColumnType) (dataType string){
	//	"tinyint":   func(detailType gorm.ColumnType) (dataType string) { return "int32" },
	//	"smallint":  func(detailType gorm.ColumnType) (dataType string) { return "int32" },
	//	"mediumint": func(detailType gorm.ColumnType) (dataType string) { return "int32" },
	//	"bigint":    func(detailType gorm.ColumnType) (dataType string) { return "int32" },
	//	"int":       func(detailType gorm.ColumnType) (dataType string) { return "int32" },
	//}
	generator.WithDataTypeMap(dataMap)
	for _, v := range models {
		//basic(generator, v)
		mysql.AutoMigrate(v)
		generator.ApplyInterface(func() {},
			generator.GenerateModel(v.TableName(), opts...))
	}
	generator.Execute()
}
func ModelOpt(collection map[string]string) []gen.ModelOpt {
	var data []gen.ModelOpt
	for columnName, newType := range collection {
		data = append(data, gen.FieldType(columnName, newType))
		data = append(data, gen.FieldGORMTag(columnName, func(tag field.GormTag) field.GormTag {
			tag.Set("serializer", "json")
			return tag
		}))
	}
	return data

}
